package com.nexgo.payment.action.inputamount;

import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.nexgo.payment.R;
import com.nexgo.payment.action.Action;
import com.nexgo.payment.action.ActionResult;
import com.nexgo.payment.action.ActionStep;
import com.nexgo.payment.action.OnActionListener;
import com.nexgo.payment.action.confirmamount.ConfirmAmountDialogFragment;
import com.nexgo.payment.constrant.SysConstant;
import com.nexgo.payment.databases.Repository;
import com.nexgo.payment.entity.TransData;
import com.nexgo.payment.ui.BaseFragment;
import com.nexgo.payment.util.ToastUtils;
import com.nexgo.payment.widget.TitleBuilder;
import com.nexgo.payment.widget.keyboard.NumKeyBoard;
import com.nexgo.payment.widget.keyboard.NumKeyBoardWithTextView;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * 金额输入界面
 */
public class InputAmountFragment extends BaseFragment implements Action<ActionStep>, InputAmountContract.View, BaseFragment.DownTimerListener {
    private static final String TRANS_DATA = "trans_data";

    @BindView(R.id.title_tv_right)
    TextView tvTitleRight;
    @BindView(R.id.tv_amount)
    TextView amount;
    @BindView(R.id.kb)
    NumKeyBoardWithTextView kb;

    private OnActionListener mListener;
    private TransData mTransData;
    private InputAmountContract.Presenter mPresenter;
    private Unbinder unbinder;

    public InputAmountFragment() {
        // Required empty public constructor
    }

    public static InputAmountFragment newInstance(TransData transData) {
        InputAmountFragment fragment = new InputAmountFragment();
        Bundle args = new Bundle();
        args.putParcelable(TRANS_DATA, transData);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mTransData = getArguments().getParcelable(TRANS_DATA);
        }
        new InputAmountPresenter(this, Repository.getInstance(), mTransData);
    }

    @Override
    protected View initView(LayoutInflater inflater, ViewGroup container) {
        View view = inflater.inflate(R.layout.fragment_input_amount, container, false);
        unbinder = ButterKnife.bind(this, view);

        initTitle(view);

        return view;
    }

    //初始化标题栏
    private void initTitle(View view) {
        new TitleBuilder(view)
                .setExternalTitleBgRes(R.drawable.bg_blue_icon)
                .setLeftImage(R.drawable.arrow_icon)
                .setTitleText(getString(R.string.trans_amount))
                .build();
    }

    @Override
    protected void initEvent() {

    }

    @Override
    protected void initData() {
        kb.setTextView(amount);
        // 设置小数点位数
        kb.setFloat(SysConstant.FUND_DIGITS);
        // 设置可输入的最大长度
        kb.setMaxLen(12);

        kb.setMaxValue(999999999999L);
        kb.setCallback(kbCallback);
        //启动计时器
        setDownTimer(SysConstant.TIME_OUT_60, this);
    }

    @Override
    public void onResume() {
        super.onResume();
        mPresenter.start();
    }

    @OnClick({R.id.title_iv_left})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.title_iv_left:
                if (mListener != null) {
                    mListener.setActionResult(new ActionResult(this, ActionResult.ERR_CANCEL, null));
                }
                break;
            default:
                break;
        }
    }

    /**
     * 输入键盘监听回调
     */
    private NumKeyBoardWithTextView.Callback kbCallback = new NumKeyBoard.Callback() {
        @Override
        public void onKey(NumKeyBoard.KEY_TYPE keyType) {
            mPresenter.pressKey(keyType);
            switch (keyType) {
                case KEY_CANCEL:
                    if (mListener != null) {
                        mListener.setActionResult(new ActionResult(InputAmountFragment.this, ActionResult.ERR_CANCEL, null));
                    }
                    break;
                case KEY_CONFIRM:
                    // 如果输入的金额是0，则不要做任何处理
                    long retLong = Long.parseLong(kb.getRet());
                    if (retLong == 0) {
                        return;
                    }
                    mPresenter.importAmount(kb.getRet());
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnActionListener) {
            mListener = (OnActionListener) context;
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mPresenter.destroy();
    }

    @Override
    public void setPresenter(InputAmountContract.Presenter presenter) {
        mPresenter = presenter;
    }

    @Override
    public ActionStep getActionStep() {
        return ActionStep.INPUT_AMOUNT;
    }

    @Override
    public void showOverRefundAmount() {
        ToastUtils.showToast(getString(R.string.over_refund_amount));
    }

    @Override
    public void showConfirmAmount(String amount) {
        ConfirmAmountDialogFragment dialogFragment = ConfirmAmountDialogFragment.newInstance(amount);
        dialogFragment.setDialogListener(() -> mPresenter.confirmAmount(amount));
        dialogFragment.setCancelable(false);
        dialogFragment.show(getFragmentManager(), null);
    }

    @Override
    public void showSuccessful(String amount) {
        if (mListener != null) {
            mListener.setActionResult(new ActionResult(this, ActionResult.SUCC, amount));
        }
        //取消计时器
        cancelDownTimer();
    }

    @Override
    public boolean isActive() {
        return isAdded();
    }

    @Override
    public void onTick(long secondsUntilFinished) {
        if (!isActive()) {
            return;
        }
        tvTitleRight.setVisibility(View.VISIBLE);
        tvTitleRight.setText(String.valueOf(secondsUntilFinished));
    }

    @Override
    public void onFinish() {
        if (isActive()) {
            tvTitleRight.setText("0");
        }
        if (mListener != null) {
            mListener.setActionResult(new ActionResult(InputAmountFragment.this, ActionResult.ERR_TIMEOUT, getString(R.string.input_amount_time_out)));
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        //取消计时器
        cancelDownTimer();
        unbinder.unbind();
        mPresenter.destroy();
    }
}
